package com.study.chat;

import com.study.handler.ChatNettyClientHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.util.Scanner;

/**
 * @ClassName: ChatNettyClient
 * @Description:
 * @Date 2024/04/29 13:55
 * @Author songshaoqiu
 **/
public class ChatNettyClient {
    public static void main(String[] args) {
        //创建线程组
        NioEventLoopGroup eventExecutors = new NioEventLoopGroup();

        try {
            //创建客户端启动对象
            Bootstrap bootstrap = new Bootstrap();
            //设置相关参数
            bootstrap.group(eventExecutors)
                    //使用NioSocketChannel作为客户端的通道实现
                    .channel(NioSocketChannel.class)
                    //创建通道初始化并设置handler业务处理器
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            ChannelPipeline pipeline = socketChannel.pipeline();
                            //先配置解码器
                            pipeline.addLast(new StringDecoder());
                            //在配置编码器
                            pipeline.addLast(new StringEncoder());
                            //添加处理器
                            pipeline.addLast(new ChatNettyClientHandler());
                        }
                    });
            //客户端连接服务端
            ChannelFuture connect = bootstrap.connect("127.0.0.1", 9091);
            System.out.println("欢迎来到聊天室");
            Scanner scanner =new Scanner(System.in);
            while (scanner.hasNextLine()){
                String msx = scanner.nextLine();
                //发送消息到channel
                connect.channel().writeAndFlush(msx);
            }
            //阻塞等待完成操作后 关闭通道
            connect.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }finally {
            eventExecutors.shutdownGracefully();
        }

    }
}
